package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-mnger/cache"
	"novel-mnger/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	car_code := c.PostForm("car_code")
	car_name := c.PostForm("car_name")
	car_num := c.PostForm("car_num")
	data := models.Car{
		CarCode: car_code,
		CarName: car_name,
		CarNum:  car_num,
	}
	models.DB.Create(&data)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
	})
	return
}

func OrderAdd(c *gin.Context) {
	order_no := c.PostForm("order_no")
	from_address := c.PostForm("form_address")
	to_address := c.PostForm("to_address")
	cid, _ := strconv.Atoi(c.PostForm("cid"))

	data := models.Order{
		OrderNo:     order_no,
		FromAddress: from_address,
		ToAddress:   to_address,
		Cid:         cid,
	}
	models.DB.Create(&data)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
	})
	return
}
func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
	offset := (page - 1) * size

	/*
		SELECT
		  orders.order_no as OrderNo,
		  orders.from_address as FromAddress,
		  orders.to_address as ToAddress,
		  cars.car_code as CarCode,
		  cars.car_name as CarName,
		  cars.car_num as CarNum
		FROM
		  orders
		  LEFT JOIN cars ON cars.id = orders.cid
	*/
	var orderList []models.OrderList

	redis_key := "data_list_page_" + strconv.Itoa(page)
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheJson == "" {
		models.DB.Table("orders").
			Joins("LEFT JOIN cars ON cars.id = orders.cid").
			Select("orders.order_no as OrderNo",
				"orders.from_address as FromAddress",
				"orders.to_address as ToAddress",
				"cars.car_code as CarCode",
				"cars.car_name as CarName",
				"cars.car_num as CarNum").
			Offset(offset).
			Limit(size).Debug().Find(&orderList)
		json, _ := json.Marshal(orderList)
		cache.Rdb.Set(cache.Ctx, redis_key, json, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheJson), &orderList)
	}

	var total int64
	models.DB.Model(&models.Order{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"data":  orderList,
		"total": total,
		"msg":   "成功",
	})
	return

}
func OrderDetail(c *gin.Context) {
	id := c.Query("id")
	var order models.Order

	redis_key := "data_detail_" + id
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheJson == "" {
		models.DB.Where("id = ?", id).First(&order)
		json, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, json, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheJson), &order)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": order,
		"msg":  "成功",
	})
	return
}
